package com.bulletelc.apollopre.utils;

import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * author: lhl
 * date  : 2017/11/01
 * desc  : Base64工具类
 */

public final class Base64Util {

    private Base64Util() {
        //empty
    }

    /**
     * 将文件转成base64字符串,用于网络传输
     *
     * @param filePath
     * @return
     */
    public static String fileToBase64String(String filePath) {
        String str = null;
        try {
            File file = new File(filePath);
            FileInputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputStream.read(buffer);
            inputStream.close();
            str = Base64.encodeToString(buffer, Base64.NO_WRAP);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 将base64字符串解码保存为文件
     *
     * @param base64Str  base64的字符串
     * @param savePath  文件保存路径
     * @return true:成功,false:失败
     */
    public static boolean base64StringToFile(String base64Str,String savePath) {
        boolean result=false;
        byte[] buffer=Base64.decode(base64Str, Base64.DEFAULT);
        try {
            FileOutputStream outputStream = new FileOutputStream(savePath);
            outputStream.write(buffer);
            outputStream.close();
            result=true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String fileBase64String(String path) {

        try {
            FileInputStream fis = new FileInputStream(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = fis.read(buffer)) >= 0) {
                baos.write(buffer, 0, count);
            }
            fis.close();
            String uploadBuffer = new String(Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP));
            return uploadBuffer;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
